package com.iedu.demo.lgq.mapper;

import com.iedu.demo.lgq.entity.TbItem;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ItemMapper {

    // 查询所有商品
    @Select("SELECT * FROM tb_item ORDER BY created DESC")
    List<TbItem> findAllItems();

    // 根据条件模糊查询商品
    @Select("<script>" +
            "SELECT * FROM tb_item" +
            "<where>" +
            "<if test='title != null and title != \"\"'> AND title LIKE CONCAT('%', #{title}, '%') </if>" +
            "<if test='status != null'> AND status = #{status} </if>" +
            "</where>" +
            "ORDER BY created DESC" +
            "</script>")
    List<TbItem> findItemsByCondition(@Param("title") String title, @Param("status") String status);

    // 插入商品
    @Insert("INSERT INTO tb_item (title, sell_point, price, num, barcode, image, cid, status, created, updated) " +
            "VALUES (#{title}, #{sellPoint}, #{price}, #{num}, #{barcode}, #{image}, #{cid}, #{status}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "itemId")
    void addItem(TbItem item);

    // 更新商品信息
    @Update("UPDATE tb_item SET title = #{title}, sell_point = #{sellPoint}, price = #{price}, num = #{num}, " +
            "barcode = #{barcode}, image = #{image}, cid = #{cid}, status = #{status}, updated = NOW() WHERE item_id = #{itemId}")
    void updateItem(TbItem item);

    // 删除商品（根据ID设置状态为3-删除）
    @Delete("DELETE FROM tb_item WHERE item_id = #{itemId}")
    void deleteItem(String itemId);

    @Select("SELECT * FROM tb_item WHERE item_id = #{itemId}")
    TbItem selectById(String itemId);

    // 设置商品库存
    @Update("UPDATE tb_item SET num = #{num}, updated = NOW() WHERE item_id = #{itemId}")
    void setItemStock(@Param("itemId") String itemId, @Param("num") String num);

    @Select("SELECT * FROM tb_item LIMIT #{offset}, #{pageSize}")
    List<TbItem> getItemList(@Param("offset") int offset, @Param("pageSize") int pageSize);

    @Select("<script>" +
            "SELECT * FROM tb_item " +
            "WHERE cid = #{categoryId} " +
            "<if test='keyword != null and keyword != \"\"'>" +
            "AND title LIKE #{keyword} " +
            "</if>" +
            "LIMIT #{offset}, #{pageSize}" +
            "</script>")
    List<TbItem> getItemsByCategory(@Param("categoryId") String categoryId,
                                    @Param("keyword") String keyword,
                                    @Param("offset") int offset,
                                    @Param("pageSize") int pageSize);
}
